package com.yzq.os.spider.v.dao;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * 抽象数据访问类
 * @author 苑志强(xingyu_yzq@163.com)
 *
 */
@Repository
public abstract class AbstractDao {
	protected Logger logger = Logger.getLogger(getClass());

	/**
	 * MYSQL主
	 */
	@Autowired
	@Qualifier("jdbcTemplateOnline")
	protected JdbcTemplate jdbcTemplateOnline;

	/**
	 * MYSQL从
	 */
	@Autowired
	@Qualifier("jdbcTemplateOffline")
	protected JdbcTemplate jdbcTemplateOffline;

	/**
	 * 判断表是否存在于（主）库中
	 * 
	 * @param tableName
	 * @return
	 */
	public boolean isExistTableOnlineDatabase(String tableName) {
		return isExistTable(tableName, jdbcTemplateOnline);
	}

	/**
	 * 判断表是否存在于（从）库中
	 * 
	 * @param tableName
	 * @return
	 */
	public boolean isExistTableOfflineDatabase(String tableName) {
		return isExistTable(tableName, jdbcTemplateOffline);
	}

	/**
	 * 判断表是否存在
	 * 
	 * @param tableName
	 * @param jt
	 * @return
	 */
	protected boolean isExistTable(String tableName, JdbcTemplate jt) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select count(*) ");
		sql.append("   from information_schema.tables ");
		sql.append("  where table_name = ? ");

		logger.debug("SQL:[" + sql.toString() + "],tableName:[" + tableName
				+ "]");

		int count = jt.queryForInt(sql.toString(), tableName);
		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 从（主）库中删除表
	 * 
	 * @param tableName
	 */
	public void dropOnlineTable(String tableName) {
		dropTable(tableName, jdbcTemplateOnline);
	}

	/**
	 * 从（从）库中删除表
	 * 
	 * @param tableName
	 */
	public void dropOfflineTable(String tableName) {
		dropTable(tableName, jdbcTemplateOffline);
	}

	/**
	 * 删除表
	 * 
	 * @param tableName
	 * @param jt
	 */
	private void dropTable(String tableName, JdbcTemplate jt) {
		String sql = " drop table if exists `" + tableName + "` ";
		logger.debug("Drop table SQL:[" + sql + "]");
		jt.execute(sql);
	}

	/**
	 * 统计（主）库表记录数
	 * 
	 * @param tableName
	 * @return
	 */
	public int countOnlineTable(String tableName) {
		String sql = " select count(1) from " + tableName + " ";
		return jdbcTemplateOnline.queryForInt(sql);
	}

	/**
	 * 统计（从）库表记录数
	 * 
	 * @param tableName
	 * @return
	 */
	public int countOfflineTable(String tableName) {
		String sql = " select count(1) from " + tableName + " ";
		return jdbcTemplateOffline.queryForInt(sql);
	}

}
